package com.lph.health.controller;

import com.lph.health.service.SysUserService;
import com.lph.health.utils.*;
import com.lph.health.vo.LoginVo;
import com.lph.health.vo.MailVo;
import com.lph.health.vo.WxLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;


/**
 * 登录
 * 退出
 * 获取用户信息
 */

@RestController
@RequestMapping("/user")
@Api(tags = "登录")
@Slf4j
public class LoginController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MailUtil mailUtil;

    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        return sysUserService.login(loginVo);
    }

    @ApiOperation(value ="获取用户基本信息")
    @GetMapping("/getInfo")
    public Result getUserInfo(){
        return Result.success("获取用户信息成功！", SecurityUtil.getUser());
    }

    @ApiOperation(value ="登出接口")
    @GetMapping("/logout")
    public Result logout(){
        // 清除缓存
        redisUtil.delKey("userInfo_" + SecurityUtil.getUserName());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null){
            SecurityContextHolder.getContext().setAuthentication(null);  // 清空security
        }
        return Result.success("退出成功！");
    }

    @ApiOperation(value = "邮箱登录")
    @PostMapping("/mail/login")
    public Result mailLogin(@RequestBody LoginVo loginVo) {
        return sysUserService.login(loginVo);
    }

    /**
     * 微信邮箱发送验证码
     * @param mail
     * @return
     */
    @PostMapping("/sendMail")
    public Result sendMail(String mail){
        MailVo mailVo = new MailVo();
        mailVo.setSubject("健康计划定制服务平台--微信登录");
        Integer code = ValidateCodeUtil.generateValidateCode(6);
        mailVo.setContent("您的验证码为："+ code +" 有效期为5分钟，请注意使用!");
        String[] receivers = new  String[1];
        receivers[0] = mail;
        mailVo.setReceivers(receivers);
        log.info("receivers:{}"+receivers);
        redisUtil.setValueTime( mail + "mailCode", code, 5);
        return Result.success("验证码发送成功！", mailUtil.sendMail(mailVo));
    }

    @ApiOperation("微信登录")
    @PostMapping("/wxlogin")
    public Result wxlogin(@RequestBody WxLoginVo wxLoginVo) {
        return sysUserService.wxlogin(wxLoginVo);
    }

    @GetMapping("/runLogin")
    public Result runLogin(String code) {
        return sysUserService.runLogin(code);
    }

    @ApiOperation("获取用户信息")
    @PostMapping("/getUserInfo")
    public Result getUserInfo(String email) {
        return sysUserService.getUserInfo(email);
    }
}
